<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\User as UserModel;
use app\api\model\UserCoupon as UserCouponModel;
use app\api\service\User as UserService;
use app\common\service\qrcode\TimePoster as PosterService;
use cores\exception\BaseException;
use think\facade\Db;
use think\response\Json;

/**
 * 用户管理
 * Class User
 * @package app\api\controller
 */
class User extends Controller {
	/**
	 * 当前用户详情
	 * @return Json
	 * @throws BaseException
	 */
	public function info(): Json {
		// 当前用户信息
		$userInfo = UserService::getCurrentLoginUser(true);
		// 获取用户头像
		$userInfo['avatar'];
		// 获取会员等级
		$userInfo['grade'];
		return $this->renderSuccess(compact('userInfo'));
	}
	public function getPoster() {

		$userInfo = UserService::getCurrentLoginUser();
		// 获取用户头像
		$userInfo['avatar'];
		// 生成二维码
		$Qrcode = new PosterService($userInfo);
		return $this->renderSuccess(['imageUrl' => $Qrcode->getImage()]);
	}
	public function getUserInfo($userId): Json {
		$user_id = UserService::getCurrentLoginUserId();
		$is_self = 0;

		$userInfo = UserModel::detail($userId, ['avatar']);

		if ($userId == $user_id) {
			$is_self = 1;
		} else {
			$log = Db::name('learn_user_guanzhu')
				->where('user_id', $user_id)
				->where('follow_id', $userId)->find();
			$userInfo['is_guanzhu'] = $log ? 1 : 0;
		}

		$time = time() - strtotime($userInfo['create_time']);
		$userInfo['day'] = round($time / 86400);
		return $this->renderSuccess(compact('userInfo', 'is_self'));
	}
	//基本数据
	public function getData(): Json {
		// 当前用户信息
		$userId = UserService::getCurrentLoginUserId(true);

		$userInfo = Db::name('user')->where('user_id', $userId)->find();

		//天数
		$data['day'] = Db::name('learn_clock_log')->where('user_id', $userId)->count();
		//条文完成比例
		$data['article_complate'] = 0;
		$article_num = Db::name('learn_article_category_user')->where('user_id', $userInfo['user_id'])->field('sum(total_num) as total_num,sum(complate_num) as complate_num')->find();
		if ($article_num && $article_num['total_num'] > 0) {
			$data['article_complate'] = round($article_num['complate_num'] / $article_num['total_num'] * 100, 2);
		}

		//理论完成比例
		$data['book_complate'] = 0;
		$article_num = Db::name('learn_book_category_user')->where('user_id', $userInfo['user_id'])->field('sum(total_num) as total_num,sum(complate_num) as complate_num')->find();
		if ($article_num && $article_num['total_num'] > 0) {
			$data['book_complate'] = round($article_num['complate_num'] / $article_num['total_num'] * 100, 2);
		}

		$data['book_id'] = $userInfo['book_id'];
		$data['article_id'] = $userInfo['article_id'];

		return $this->renderSuccess(compact('data'));
	}
	//打卡记录
	public function getClockLog($date = ''): Json {
		if ($date == '') {
			$date = date('Y-m-d');
		}

		// 当前用户信息
		$userId = UserService::getCurrentLoginUserId(true);
		$article_time = Db::name('learn_article_title_user')
			->where('date', $date)
			->where('user_id', $userId)
			->sum('time');

		$book_time = Db::name('learn_book_user')->where('date', $date)->where('user_id', $userId)
			->sum('time');

		$all_time = $article_time + $book_time;

		$hour = round($article_time / 3600);

		$second = $article_time % 3600;
		$minute = round($second / 60);

		$time = $hour > 0 ? $hour . 'H' : '';
		$time .= $minute . 'min';

		$data['article_time'] = $time;

		$hour = round($book_time / 3600);

		$second = $book_time % 3600;
		$minute = round($second / 60);

		$time = $hour > 0 ? $hour . 'H' : '';
		$time .= $minute . 'min';

		$data['book_time'] = $time;

		$hour = round($all_time / 3600);

		$second = $all_time % 3600;
		$minute = round($second / 60);

		$time = $hour > 0 ? $hour . 'H' : '';
		$time .= $minute . 'min';

		$data['all_time'] = $time;

		$next_month = date("Y-m-01", strtotime("+1 month"));
		$list = Db::name('learn_clock_log')
			->where('date', '>=', Date('Y-m-01'))
			->where('date', '<', $next_month)
			->where('user_id', $userId)->select()->toArray();
		foreach ($list as &$item) {
			$item['date'] = Date('Y-m-d', $item['create_time']);
		}

		return $this->renderSuccess(compact('list', 'data'));
	}
	/**
	 * 账户资产
	 * @return Json
	 * @throws BaseException
	 */
	public function assets(): Json {
		// 当前用户信息
		$userInfo = UserService::getCurrentLoginUser(true);
		// 用户优惠券模型
		$model = new UserCouponModel;
		// 返回数据
		return $this->renderSuccess([
			'assets' => [
				'balance' => $userInfo['balance'], // 账户余额
				'points' => $userInfo['points'], // 会员积分
				'coupon' => $model->getCount($userInfo['user_id']), // 优惠券数量(可用)
			],
		]);
	}
	/**
	 * 关注
	 * @return Json
	 * @throws BaseException
	 */
	public function guanzhu(): Json {
		$model = new UserModel;
		if (!$model->guanzhu($this->postForm())) {
			return $this->renderSuccess($model->getError() ?: '操作失败');
		}
		return $this->renderSuccess('成功');
	}

	/**
	 * 手机号绑定
	 * @return Json
	 * @throws BaseException
	 */
	public function bindMobile(): Json {
		$model = new UserModel;
		if (!$model->bindMobile($this->postForm())) {
			return $this->renderSuccess($model->getError() ?: '操作失败');
		}
		return $this->renderSuccess('恭喜您，手机号绑定成功');
	}

	/**
	 * 修改个人信息（头像昵称）
	 * @return Json
	 * @throws BaseException
	 */
	public function personal(): Json {
		$model = new UserModel;
		if (!$model->personal($this->postForm())) {
			return $this->renderSuccess($model->getError() ?: '操作失败');
		}
		return $this->renderSuccess('恭喜您，信息修改成功');
	}
}
